﻿using System.Collections.Generic;
using System.IO;
using NaughtyAttributes;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif


public class FixMeshTools : MonoBehaviour
{
    public string path = "Assets/SuperCombiner/Combined/Prefabs/";
    public string prefix = "Buildings";

#if UNITY_EDITOR
    private GameObject[] GetObjs()
    {
        var objList = new List<GameObject>();
        var info = new DirectoryInfo(path);
        var files = info.GetFiles("*", SearchOption.AllDirectories);
        for (var i = 0; i < files.Length; i++)
        {
            if (files[i].Name.EndsWith(".meta")) continue;
            var obj = AssetDatabase.LoadAssetAtPath<GameObject>(string.Format("{0}{1}", path, files[i].Name));
            objList.Add(obj);
        }

        return objList.ToArray();
    }

    private GameObject GetObj(GameObject[] objs, string name)
    {
        for (var i = 0; i < objs.Length; i++)
            if (objs[i].name == string.Format("{0}_{1}", prefix, name))
                return objs[i];
        return null;
    }

    [Button]
    public void Fix()
    {
        Fix(gameObject);
    }

    public void Fix(GameObject obj)
    {
        var objs = GetObjs();
        for (var i = 0; i < obj.transform.childCount; i++)
        {
            var item = obj.transform.GetChild(i).gameObject;
            if (item.transform.childCount > 0) Fix(item);
            var fixItem = GetObj(objs, item.name.Split(" ")[0]);
            if (fixItem == null)
            {
                Debug.LogErrorFormat("Fix item->{0}", item.name);
                continue;
            }

            var filter = item.GetComponent<MeshFilter>();
            if (filter != null) filter.sharedMesh = fixItem.GetComponent<MeshFilter>().sharedMesh;
            var renderer = item.GetComponent<MeshRenderer>();
            if (renderer != null) renderer.sharedMaterials = fixItem.GetComponent<MeshRenderer>().sharedMaterials;
        }
    }
#endif
}